package pagerank.controller;

import java.net.InetAddress;
import java.net.Socket;
import java.net.URLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public class PageRankService {

    static private int dataCenterIdx = 0;

    /**
     * List of available google datacenter IPs and addresses
     */
    static final public String [] GOOGLE_PR_DATACENTER_IPS = new String[]{
                
                "toolbarqueries.google.com",
                "toolbarqueries.google.com.vn"
                };

    /**
     * Default constructor
     */
    public PageRankService() {

    }

    /**
     * Must receive a domain in form of: "http://www.domain.com"
     * @param domain - (String)
     * @return PR rating (int) or -1 if unavailable or internal error happened.
     */
    public int getPR(String domain) {

        int result = -1;
        JenkinsHash jHash = new JenkinsHash();

        String googlePrResult = "";

        long hash = jHash.hash(("info:" + domain).getBytes());

        String url = "http://"+GOOGLE_PR_DATACENTER_IPS[dataCenterIdx]+"/tbr?client=navclient-auto&hl=en&"+
                "ch=6"+hash+"&ie=UTF-8&oe=UTF-8&features=Rank&q=info:" + domain;

        try {
        	Random random = new Random();
        	List<String> listSock = new ArrayList<String>();
			listSock.add("184.107.74.40");
			listSock.add("184.107.74.41");
			listSock.add("184.107.74.42");
			listSock.add("184.107.74.43");
			listSock.add("184.107.74.44");
			listSock.add("184.107.74.45");
			listSock.add("184.107.74.46");
			listSock.add("184.107.74.47");
			int rand = new Random().nextInt(7);
        	Socket sockket = new Socket(GOOGLE_PR_DATACENTER_IPS[dataCenterIdx], 80, InetAddress.getByName(listSock.get(rand)), random.nextInt(1000)+30000);
//			Socket sockket = new Socket(GOOGLE_PR_DATACENTER_IPS[dataCenterIdx], 80);
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(sockket.getOutputStream()));
			
			writer.write("GET /tbr?client=navclient-auto&hl=en&"+"ch=6"+hash+"&ie=UTF-8&oe=UTF-8&features=Rank&q=info:"+domain+" HTTP/1.1\r\n");
			writer.write("Host: "+GOOGLE_PR_DATACENTER_IPS[dataCenterIdx]+"\r\n");
			writer.write("Referer: http://5ty.org\r\n");
			
			writer.write("User-Agent:	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1) Gecko/20100101 Firefox/8.0.1\r\n");
			writer.write("Connection:	Close\r\n");
			
			
			writer.write("\r\n\r\n");
			writer.flush();
			BufferedReader reader =  new BufferedReader(new InputStreamReader(sockket.getInputStream()));
			String content = "";
			while(1==1)
			{
				String str = reader.readLine();
				if(str==null) break;
				content+=str;
			}
        	
//			System.out.println(content);
//        	
//            URLConnection con = new URL(url).openConnection();
//            InputStream is = con.getInputStream();
//            byte [] buff = new byte[1024];
//            int read = is.read(buff);
//            while (read > 0) {
//                googlePrResult = new String(buff, 0, read);
//                read = is.read(buff);
//            }
            googlePrResult = content;

            String[] prResult = googlePrResult.split(":");
 
            result = new Long(prResult[prResult.length-1]).intValue();
        } catch (Exception e) {
            e.printStackTrace();
        }

        dataCenterIdx++;
        if (dataCenterIdx == GOOGLE_PR_DATACENTER_IPS.length) {
            dataCenterIdx = 0;
        }

        return result;

    }

    public static void main(String [] args) {
        long start = System.currentTimeMillis();
        PageRankService prService = new PageRankService();
        String domain = "http://www.gmail.com";
        if (args.length > 0) {
            domain = args[0];
        }
        System.out.println("Checking " + domain);
        System.out.println("Google PageRank: " + prService.getPR(domain));
        System.out.println("Took: " + (System.currentTimeMillis() - start) + "ms");
    }
}
